<template>
  <div id="app">
    <div>
      <span>姓名: </span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄: </span>
      <input type="number" v-model.number="uage" />
    </div>
    <div>
      <span>性别: </span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-show="arr.length > 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, i) in arr" :key="i">
          <td>{{ i + 1 }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.sex }}</td>
          <td>
            <button @click="delFn(i)">删除</button>
            <button @click="bj(i)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: "",
      uage: 0,
      gender: "",
      uindex: null, // 保存正在编辑的对象索引，不能给0或0以上的值
      arr: [
        {
          name: "鸣人",
          age: 19,
          sex: "男",
        },
        {
          name: "雏田",
          age: 16,
          sex: "女",
        },
      ],
    };
  },
  methods: {
    addFn() {
      // 添加修改点击事件
      let obj = {
        name: this.uname,
        age: this.uage,
        sex: this.gender,
      };

      if (this.uindex !== null) {
        this.$set(this.arr, this.uindex, obj);
 
        this.uindex = null;
      } else {
        this.arr.push(obj);
      }
    },
    // 删除
    delFn(i) {
      this.arr.splice(i, 1);
    },
    //  编辑
    bj(i) {
      let obj = this.arr[i];
      this.uname = obj.name;
      this.uage = obj.age;
      this.gender = obj.sex;

      this.uindex = i; //年没空的索引
    },
  },
};
</script>
